/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import beans.B_Usuario;
import db.DB_Usuario;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author JoseHernan
 */
public class C_Login extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(true);
        if (session.getAttribute("userName") == null) {
            String usuario = request.getParameter("usuario");
            String password = request.getParameter("pass");
            B_Usuario objUsuario = new B_Usuario();
            objUsuario.setUsuario(usuario);
            objUsuario.setPassword(password);
            ArrayList<String> result;
            result = DB_Usuario.authentication(objUsuario);
            if (result.get(0).equals("OK")) {
                session.setAttribute("userName", result.get(1));
                session.setAttribute("idUsuario", result.get(2));
                out.write(result.get(0));
            } else {
                out.write(result.get(0));
            }
        } else {
            //WITH SESSION
            session.setAttribute("userName", session.getAttribute("userName").toString());
            response.sendRedirect("home.jsp");
        }

    }
}
